﻿using FlexFlow.Base.Interface;
using FlexFlow.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlexFlow.Runtime
{
    /// <summary>
    /// 表示应用程序池
    /// </summary>
    public class InProcApplicationPool : IApplicationPool
    {
        private Dictionary<ApplicationDefine, IWorkFlowApplication> _registeredApplications = new Dictionary<ApplicationDefine, IWorkFlowApplication>();

        /// <summary>
        /// 向应用程序池注册指定的工作流引擎执行程序
        /// </summary>
        /// <param name="actType">
        /// 要注册的执行程序对应的活动类型
        /// </param>
        /// <param name="app">
        /// 要注册的执行程序
        /// </param>
        /// <param name="procId">
        /// 要注册的执行程序所在的流程ID，如果该参数为空，则注册为默认活动处理程序
        /// </param>
        /// <param name="actDescription">
        /// 活动类型描述
        /// </param>
        /// <param name="cssClass">
        /// 应用程序节点在前台展示的样式
        /// </param>
        /// <returns>
        ///  注册结果，成功为true，失败为false
        /// </returns>
        public bool RegisterApplication(String actType, IWorkFlowApplication app, Guid? procId = null, string actDescription = "",string cssClass = "")
        {
            ApplicationDefine appDef = new ApplicationDefine()
            {
                ApplicationClassFullName = app.GetType().FullName,
                ProcessId = procId,
                ActivityType = actType,
                ActivityDescription = actDescription,
                CssClass = cssClass
            };
            _registeredApplications[appDef] = app;
            return true;
        }
        /// <summary>
        /// 取得已经注册的应用程序列表
        /// </summary>
        /// <returns>
        /// 已经注册的应用程序列表
        /// </returns>
        public ApplicationDefine[] GetRegisteredApplications()
        {
            return _registeredApplications.Keys.ToArray();
        }
        /// <summary>
        /// 取得与指定类型的活动绑定的工作流执行程序
        /// </summary>
        /// <param name="actType">
        /// 活动类型
        /// </param>
        /// <param name="procId">
        /// 流程ID
        /// </param>
        /// <returns>
        /// 该类型绑定的执行程序，如果执行程序不存在，则返回null
        /// </returns>
        public IWorkFlowApplication GetApplication(Guid procId, String actType)
        {
            ApplicationDefine appDef = new ApplicationDefine()
            {
                ProcessId = procId,
                ActivityType = actType
            };
            IWorkFlowApplication app = null;
            //检索流程活动处理程序
            this._registeredApplications.TryGetValue(appDef, out app);
            //检索默认活动处理程序
            if (app == null)
            {
                appDef.ProcessId = null;
                this._registeredApplications.TryGetValue(appDef, out app);
            }
            return app;
        }
    }
}
